package com.slz3.business.module.apiAliyun.aliyunOSS.steward;

import com.slz3.business.frame.module.ApiClients;
import com.slz3.business.frame.response.RR;
import com.slz3.business.frame.response.ResInfo;
import com.slz3.business.frame.util.VE;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.nio.file.Path;

import static java.nio.file.Files.createTempFile;

public class AliyunOSSResponse {

    /**
     * postman 已经实现上传获取到 md5 ，请通过 md5 获取 文件 url 反馈给客户端
     */
    public static Mono<ServerResponse> uploadObject(ServerRequest req) {
        return req.multipartData().flatMap(item -> {
                    FilePart filePart = (FilePart) item.getFirst("file");
                    Path tempFile = null;
                    try {
                        tempFile = createTempFile("uploadObject", filePart.filename());
                    } catch (IOException e) {
                        RR.resDetail(req).put("errMsg", e.getMessage());
                        e.printStackTrace();
                    }
                    if (VE.isNotEmpty(tempFile)) {
                        filePart.transferTo(tempFile.toFile());
                        String fileUrl = ApiClients.aliyunOSS.uploadObject(tempFile.toFile());
                        RR.resDetail(req).put("fileUrl", fileUrl);
                        RR.resInfo(req).setLink(fileUrl); // Froala Editor
                        return RR.success(req, ResInfo.builder().code(RR.SUCCESS).build());
                    } else {
                        return RR.error(req, ResInfo.builder().theme("upload fail").description("create temp file fail").code(RR.EXCEPTION).build());
                    }
                }
        );
    }

}
